﻿using BLL.Enums;
using Common;
using DevExpress.Data.Filtering;
using DevExpress.Xpo;
using Model;
using Model.Bill;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;

namespace BLL
{
    public class OrderBLL
    {
        StockDetailBLL stock = new StockDetailBLL();
        public string Payment(TB_Order order)
        {
            Session s = order.Session;
            StringBuilder sbMsg = new StringBuilder();
            try
            {
                s.BeginTransaction();
                order.PayStatusID = (int)PaymentStatus.Complete;
                order.StatusID = (int)OrderStatus.Complete;
                order.Save();

                TB_OrderPay op;
                if (order.TypeID == (int)OrderType.Delivery)
                {
                    op = s.FindObject<TB_OrderPay>(CriteriaOperator.Parse("OrderID=?", order.OrderID));
                }
                else 
                {
                    op = new TB_OrderPay(s);
                }
                op.OrderID = order;
                op.StatusID =(int)PaymentStatus.Complete;
                op.Amount = order.ActualAmount;
                op.AmountCope =0;
                op.PayDate = DateTime.Now;
                op.Save();

                foreach (TB_OrderDetail od in order.OrderDetails)
                {
                    string msg = stock.StockLess(od.WarehouseID.WarehouseID, od.ProductID.ProductID, od.Quantity, s, false);
                    if (!string.IsNullOrEmpty(msg))
                        sbMsg.Append(msg);
                }
                if (sbMsg.Length > 0)
                    s.RollbackTransaction();
                else
                    s.CommitTransaction();
            }
            catch (Exception ex)
            {
                s.RollbackTransaction();
                sbMsg.Append(ex.Message);
            }
            return sbMsg.ToString();
        }
        public string PaymentDelivery(TB_Order order)
        {
            Session s = order.Session;
            StringBuilder sbMsg = new StringBuilder();
            try
            {
                s.BeginTransaction();
                order.PayStatusID = (int)PaymentStatus.Editor;
                order.StatusID = (int)OrderStatus.Delivery;
                order.Save();

                TB_OrderPay op = new TB_OrderPay(s);
                op.OrderID = order;
                op.StatusID = (int)PaymentStatus.Editor;
                op.Amount=0;
                op.AmountCope = order.CopeAmount;
                op.Save();

                foreach (TB_OrderDetail od in order.OrderDetails)
                {
                    string msg = stock.StockLess(od.WarehouseID.WarehouseID, od.ProductID.ProductID, od.Quantity, s, false);
                    if (!string.IsNullOrEmpty(msg))
                        sbMsg.Append(msg);
                }
                if (sbMsg.Length > 0)
                    s.RollbackTransaction();
                else
                {
                    s.CommitTransaction();
                    string wxMsgUrl=ConfigurationManager.AppSettings["WxMsgUrl"];
                    //LY.WxExtend.MessageTemplate.BaseMsg msg = new LY.WxExtend.MessageTemplate.BaseMsg();
                    //msg.openId = "oYBhUwQOtrhIFt1hoAU5wh78t_wI";
                    //msg.templateId = "R7IUvvJ4i6wEsxlZ_9cqKhsYQnXg1709EoITuBKECBA";
                    //msg.url = "";
                    //msg.first = "尊敬的小新，您的订单（121185885425）已下单成功！";
                    //msg.keyword1 = "粮油";
                    //msg.keyword2 = order.CopeAmount.ToString("f2");
                    //msg.keyword3 = "送货中";
                    //msg.remark = "您的订单我们已下单，接下来我们将会按排人员进行发货，敬请留意！";
                    //MyHttpWebRequest.Post(wxMsgUrl, JsonConvert.SerializeObject(msg));
                }
            }
            catch (Exception ex)
            {
                s.RollbackTransaction();
                sbMsg.Append(ex.Message);
            }
            return sbMsg.ToString();
        }
        public void CalcOrderAmount(TB_Order order)
        {
            order.CopeAmount = 0;
            order.LowestAmount = 0;
            foreach (TB_OrderDetail od in order.OrderDetails)
            {
                order.CopeAmount = order.CopeAmount + od.TurnoverPrice * od.Quantity;
                order.LowestAmount = order.LowestAmount + od.SalePriceLowest * od.Quantity;
            }
            order.Save();
        }
        public void UploadOrder(TB_Order order)
        {
            order.Reload();
            API.Order.MTB_Order mOrder = new API.Order.MTB_Order();
            mOrder.OrderID = order.OrderID;
            mOrder.BillCode = order.BillCode;

            //mOrder.StatusID = order.StatusID;
            //mOrder.TypeID = order.TypeID;
            //mOrder.PayStatusID = order.PayStatusID;
            //mOrder.StoreID = order.StoreID;
            //mOrder.ProviderID = order.ProviderID;
            //mOrder.SellDate = order.SellDate;
            //mOrder.DeliveryDate = order.DeliveryDate;
            mOrder.ContactUser = order.ContactUser;
            mOrder.ContactPhone = order.ContactPhone;
            mOrder.EmployeeID1 = order.EmployeeID1;
            mOrder.EmployeeID2 = order.EmployeeID2;
            //mOrder.CopeAmount = order.CopeAmount;
            //mOrder.ActualAmount = order.ActualAmount;
            //mOrder.Creator = order.Creator;
            //mOrder.CreateDT = order.CreateDT;
            //mOrder.Operator = order.Operator;
            //mOrder.UpdateDT = order.UpdateDT;
            mOrder.Remark = order.Remark;
            foreach (TB_OrderDetail od in order.OrderDetails)
            {
                order.CopeAmount = order.CopeAmount + od.TurnoverPrice * od.Quantity;
                order.LowestAmount = order.LowestAmount + od.SalePriceLowest * od.Quantity;
            }
            order.Save();
        }
        public DataTable Print(TB_Order order, out Hashtable lst) 
        {
            lst = new Hashtable();
            lst.Add("单号", order.BillCode);
            lst.Add("店柜名称", MemberInfo.Store.StoreName);
            lst.Add("打印日期", DateTime.Now.AddSeconds(15).ToString());
            lst.Add("送货日期", order.SellDate.ToShortDateString());
            lst.Add("购货单位", order.ProviderID.ProviderName);
            lst.Add("联系人", order.ContactUser);
            lst.Add("联系电话", order.ContactPhone);

            lst.Add("恩施店电话", "0718-8026218");
            lst.Add("恩师店地址", "恩施市华硒生态园7栋7号门店");
            lst.Add("恩师店营业执照", "422801600195752");
            lst.Add("恩师店许可证", "SP4228011150031787");
            lst.Add("来凤店电话", "0718-6275715");
            lst.Add("来凤店地址", "和平路27(老公安局斜对面)");
            lst.Add("来凤店营业执照", "422827600006884");
            lst.Add("来凤店许可证", "SP4228271150004508");

            lst.Add("制单人", "余以迁");
            lst.Add("配送人", "余以迁");
            lst.Add("投诉电话", "13986860299");
            lst.Add("业务员", "余以迁");

            DataTable dt = new DataTable();
            dt.Columns.Add("SimpleCode", typeof(string));
            dt.Columns.Add("ItemName", typeof(string));
            dt.Columns.Add("SpecDesc", typeof(string));
            dt.Columns.Add("BrandName", typeof(string));
            dt.Columns.Add("Unit", typeof(string));
            dt.Columns.Add("Qty", typeof(decimal));
            dt.Columns.Add("TurnoverPrice", typeof(decimal));
            dt.Columns.Add("TurnoverAmount", typeof(decimal));
            dt.Columns.Add("ProduceDate", typeof(string));
            dt.Columns.Add("ShelfDate", typeof(string));
            foreach (TB_OrderDetail od in order.OrderDetails)
            {
                DataRow row = dt.NewRow();
                row["SimpleCode"] = od.ProductID.ProductCode;
                row["ItemName"] = od.ProductID.ProductName;
                row["SpecDesc"] = od.ProductID.ProductSpec;
                row["BrandName"] =(od.ProductID.BrandID==null?"":od.ProductID.BrandID.BrandName);
                row["Unit"] = od.ProductID.Unit;
                row["Qty"] = od.Quantity;
                row["TurnoverPrice"] = od.TurnoverPrice;
                row["TurnoverAmount"] = od.TurnoverAmount;
                dt.Rows.Add(row);
            }
            return dt;
        }
    }
}
